/**
 * 
 */
package com.qdairlines.service.file.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.qdairlines.common.TraceUtil;
import com.qdairlines.dao.file.FastDFSFileMapper;
import com.qdairlines.entity.file.FastDFSFile;
import com.qdairlines.service.file.FastDFSClientService;
import com.qdairlines.service.file.FastDFSFileService;


/**
 * @author pangyannan
 * @date 2016年12月12日
 * @company QingDao Airlines
 * @description  FastDFS上传文件管理服务，将上传的文件信息保存到数据库中
 */
@Service
public class FastDFSFileServiceImpl  implements FastDFSFileService{
	private static Logger logger = Logger.getLogger(FastDFSFileServiceImpl.class);
	@Autowired
	private FastDFSFileMapper mapper;
	@Autowired
	private FastDFSClientService fastDFSClientService;
		

	@Override
	public String add(String workcode,String type,String typeKey,MultipartFile multipartFile) {
		String fastdfsFilesId = "0";
		//上传文件到FastDFS，得到上传后的id字符串
		String fastdfsKey = fastDFSClientService.uploadFile(multipartFile);

		//如果上传成功，则开始写入附件表数据库，并返回数据库的主键
		if (fastdfsKey !=null){
			FastDFSFile fastDFSFile = new FastDFSFile();
			fastDFSFile.setFastdfsFilesId(UUID.randomUUID().toString());
			fastDFSFile.setFastdfsKey(fastdfsKey);
			fastDFSFile.setFileName(multipartFile.getOriginalFilename());
			fastDFSFile.setFileKb((int) (multipartFile.getSize()/1024));
			fastDFSFile.setCreateTime(new Date());
			fastDFSFile.setCreateBy(workcode);
			fastDFSFile.setType(type);
			fastDFSFile.setTypeKey(typeKey);
			
			try {
				 mapper.insertSelective(fastDFSFile);
				 fastdfsFilesId = fastDFSFile.getFastdfsFilesId();
			} catch (Exception e) {
				//如果保存失败，则删除附件
				fastdfsFilesId = "0";
				fastDFSClientService.deleteFile(fastdfsKey);
				logger.error(TraceUtil.getTrace(e));
			}
			

		}
		return fastdfsFilesId;

	}


	@Override
	public int deleteById(String workcode, String fastdfsFilesId,DELETE_TYPE type) {
		//如果上传人工号为空，或者附件大小为0，则返回错误码0
		if(StringUtils.isEmpty(workcode) || StringUtils.isEmpty(fastdfsFilesId) ){
			return 0;
		}
		
		FastDFSFile fastDFSFile =  mapper.selectByPrimaryKey(fastdfsFilesId);
		
		
		if(fastDFSFile !=null && DELETE_TYPE.TRUE.equals(type)){
			//物理删除
			//删除FastDFS中的文件，返回0，删除成功，非0删除失败
			int deleteFlag = fastDFSClientService.deleteFile(fastDFSFile.getFastdfsKey());
			if (deleteFlag != 0 ){return 0;}
			
			//删除成功后，删除数据中的数据
			return mapper.deleteByPrimaryKey(fastdfsFilesId);
		
			
		}else if(fastDFSFile !=null && DELETE_TYPE.LOGIC.equals(type)){
			//逻辑删除
			FastDFSFile fastDFSFileDelete = new FastDFSFile();
			fastDFSFileDelete.setFastdfsFilesId(fastdfsFilesId);
			fastDFSFileDelete.setDeleteTime(new Date());
			fastDFSFileDelete.setDeleteBy(workcode);
			return mapper.updateByPrimaryKeySelective(fastDFSFileDelete);
		}else{
			return 0;
		}
		
		
	}


	@Override
	public FastDFSFile findById(String fastdfsFilesId) {
		return mapper.selectByPrimaryKey(fastdfsFilesId);
	}


	@Override
	public String getFastdfsKey(String fastdfsFilesId) {
		return this.findById(fastdfsFilesId).getFastdfsKey();
	}


	@Override
	public ResponseEntity<byte[]> downloadFileById(String fastdfsFilesId) {
		FastDFSFile fastDFSFile = mapper.selectByPrimaryKey(fastdfsFilesId);
		if(fastDFSFile != null){
			//由于文件名是从数据库中查询得到，故在下载时使用转码下载，防止中文乱码
			ResponseEntity<byte[]> responseEntity  = fastDFSClientService.downloadFileTranscoding(fastDFSFile.getFastdfsKey(), fastDFSFile.getFileName());
			return responseEntity;
		}else{
			return null;
		}
	}

	@Override
	public List<FastDFSFile> getListBy(String fastdfsFilesIds) {
		List<FastDFSFile> list = new ArrayList<FastDFSFile>();
		String[] idStrs = fastdfsFilesIds.split(",");
		for(String idStr:idStrs){
			//int id = Integer.valueOf(idStr);
			list.add(this.findById(idStr));
		}
		
		return list;
	}

	@Override
	public List<FastDFSFile> getByTypeId(String type, String typeKey) {
		Map<String ,String> map = new HashMap<>();
		map.put("type", type);
		map.put("typeKey", typeKey);
		return mapper.selectBytypeId(map);
	}
	
	@Override
	public ResponseEntity<byte[]> getSmallImage(String fastdfsFilesId,int max) {
		FastDFSFile fastDFSFile = mapper.selectByPrimaryKey(fastdfsFilesId);
		if(fastDFSFile != null){
			//由于文件名是从数据库中查询得到，故在下载时使用转码下载，防止中文乱码
			ResponseEntity<byte[]> responseEntity  = fastDFSClientService.getSmallImage(fastDFSFile.getFastdfsKey(), fastDFSFile.getFileName(),  max);
			return responseEntity;
		}else{
			return null;
		}
	}


}
